# encoding: utf-8

import json
import urllib

def stripTags(html):
	return html.replace("<b>","").replace("</b>","").replace("&#39;","'").replace("   "," ")

def main(env):
	queryDict = {
		"q"   : env["context"]["selection"].encode("utf8"),
		"lr"  : env["prefs"]["cwGoogleSearch_language"],
		"rsz" : 8,
		"safe": env["prefs"]["cwGoogleSearch_safe"]
	}
	url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % urllib.urlencode(queryDict)
	initialData = json.loads(urllib.urlopen(url).read())['responseData']
	if initialData is None: # possible abuse
		return [("messageBox",env["static"]["cwGoogleSearch_noResultMessage"])]
	hits = initialData['results']
	desiredResultCount = (int(env["prefs"]["cwGoogleSearch_desiredResultCount"]) if env["prefs"]["cwGoogleSearch_desiredResultCount"] else queryDict["rsz"])
	for start in range(queryDict["rsz"],desiredResultCount,queryDict["rsz"]):
		queryDict["start"] = start+1
		data = json.loads(urllib.urlopen(url).read())['responseData']
		if data is None: # possible abuse
			break
		hits.extend(data['results'])
	hits = hits[:desiredResultCount]
	browseFormat = u"• %s(=%%s %%s)\n%%s" % env["static"]["cwGoogleSearch_browseName"]
	result = []
	result.append("")
	result.append(env["static"]["cw_decorativeLine"])
	result.append(env["static"]["cwGoogleSearch_resultCountFormat"] % initialData['cursor']['estimatedResultCount'])
	result.append(env["static"]["cwGoogleSearch_hitCountFormat"] % (len(hits),desiredResultCount))
	for hit in hits:
		result.append(browseFormat % (urllib.unquote(hit["titleNoFormatting"]),urllib.unquote(hit["url"]),stripTags(urllib.unquote(hit["content"]))))
	result.append(env["static"]["cw_decorativeLine"])
	result.append(env["static"]["cwGoogleSearch_more"])
	browseFormat = u"%s(=%%s)" % env["static"]["cwGoogleSearch_browseName"]
	result.append(browseFormat % initialData['cursor']['moreResultsUrl'])
	result.append(env["static"]["cw_decorativeLine"])
	result.append("")
	text = "\n".join(result)
	return [
		("htmlBox",{
			"url": initialData['cursor']['moreResultsUrl'],
			"text": text,
			"width": 640,
			"height": 480,
			"label": env["static"]["cwGoogleSearch_label"]
		}),
		("moveCursor",0)
	]
